//
//  SearchViewController.m
//  Time
//
//  Created by dllo on 16/7/29.
//  Copyright © 2016年 司昌宝. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchRecommendedModel.h"
#import "Main_Search_Recommended_TableView_Cell.h"
#import "SCB_Today_Default_detail_ViewController.h"
#import "Main_Search_Edit_TableView_Cell.h"
#import "SearchArticleModel.h"

#warning continue
@interface SearchViewController ()
<
UITextFieldDelegate,
UITableViewDelegate,
UITableViewDataSource
>
/**
 *  搜索块
 */
@property (nonatomic,retain) UIView *searchView;
/**
 *  返回按钮
 */
@property (nonatomic,retain) UIButton *backButton;
/**
 *  搜索框
 */
@property (nonatomic,retain) UITextField *searchTextField;
/**
 *  搜索的tableView
 */
@property (nonatomic,retain) UITableView *searchTableView;
/**
 *  推荐内容的数组
 */
@property (nonatomic,retain) NSMutableArray *modelArray;
/**
 *  字符串数组
 */
@property (nonatomic,retain) NSMutableArray *strArray;
/**
 *  文章数组
 */
@property (nonatomic,retain) NSMutableArray *articleArray;
/**
 *  isDetail 用来判断是否是详细内容列表
 */
@property (nonatomic,assign) BOOL isDetail;

@end

@implementation SearchViewController

-(void)dealloc{
    [_searchView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.modelArray = [NSMutableArray arrayWithCapacity:5];
    self.strArray = [NSMutableArray arrayWithCapacity:5];
    self.articleArray = [NSMutableArray arrayWithCapacity:5];
    self.isDetail = NO;
    
    [self handleRecommendedDate];
    [self createSearchView];
    [self createSearchTableView];
}

-(void)handleRecommendedDate{
    NSString *urlStr = @"http://api.pianke.me/version4.0/search/hot.php?sig=139E55C98DE8C11E3CF3B6BBB3BD4DD9";
    NSString *body = @"pageSize=10";
    NSDictionary *header = @{@"Authorization":HEADER};
    
    [SCBNetTool POST:urlStr withBody:body withBodyStyle:SCBBodyString withHeaderFile:header withResponse:SCBJSON withSuccess:^(id result) {
        NSDictionary *dictionary = result;
        NSArray *array = [dictionary valueForKey:@"data"];
        for (NSDictionary *dic in array) {
            //model
            TingContent *model = [[TingContent alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.modelArray addObject:model];
            NSLog(@"1111");
        }
        [self.searchTableView reloadData];
    } withFaolure:^(NSError *error) {
        NSLog(@"抓取数据失败%@",error);
    }];
}

-(void)createSearchView{
    self.searchView = [[UIView alloc] init];
    [self.view addSubview:self.searchView];
    [self.searchView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.top.equalTo(self.view.mas_top).offset(0);
        make.height.mas_equalTo(SWIDTH * 0.2);
    }];
    
    UIView *stripView = [[UIView alloc] init];
    stripView.backgroundColor = [UIColor blackColor];
    [self.searchView addSubview:stripView];
    [stripView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.searchView.mas_left).offset(9);
        make.right.equalTo(self.searchView.mas_right).offset(-9);
        make.bottom.equalTo(self.searchView.mas_bottom).offset(0);
        make.height.mas_equalTo(2);
    }];
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.searchView addSubview:self.backButton];
    [self.backButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.searchView.mas_right).offset(-20);
        make.top.equalTo(self.searchView.mas_top).offset(20);
        make.bottom.equalTo(self.searchView.mas_bottom).offset(-20);
        make.width.mas_equalTo(SWIDTH * 0.2 - 40);
    }];
    [self.backButton setImage:[UIImage imageNamed:@"关闭 (2).png"] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *searchImageView = [[UIImageView alloc] init];
    [self.searchView addSubview:searchImageView];
    [searchImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.searchView.mas_left).offset(20);
        make.top.equalTo(self.searchView.mas_top).offset(20);
        make.bottom.equalTo(self.searchView.mas_bottom).offset(-20);
        make.width.mas_equalTo(SWIDTH * 0.2 - 40);
    }];
    searchImageView.image = [UIImage imageNamed:@"搜索 (1).png"];
    
    self.searchTextField = [[UITextField alloc] init];
    self.searchTextField.delegate = self;
    [self.searchView addSubview:self.searchTextField];
    [self.searchTextField mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchImageView.mas_right).offset(10);
        make.right.equalTo(self.backButton.mas_left).offset(-10);
        make.top.equalTo(self.searchView.mas_top).offset(20);
        make.bottom.equalTo(self.searchView.mas_bottom).offset(-20);
    }];
    self.searchTextField.placeholder = @"Search";
    [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
}

-(void)createSearchTableView{
    self.searchTableView  = [[UITableView alloc] initWithFrame:CGRectMake(0, SWIDTH * 0.2, SWIDTH, SHEIGHT - SWIDTH * 0.2) style:UITableViewStylePlain];
    [self.view addSubview:self.searchTableView];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.searchTableView registerClass:[Main_Search_Recommended_TableView_Cell class] forCellReuseIdentifier:@"Main_Search_TableView_Cell"];
    [self.searchTableView registerClass:[Main_Search_Edit_TableView_Cell class] forCellReuseIdentifier:@"Main_Search_Edit_TableView_Cell"];
    [self.searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Main_Search_Detail_TableView_Cell"];
    
    UIView *recommendedView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, SWIDTH * 0.15)];
    self.searchTableView.tableHeaderView = recommendedView;
    UILabel *recommendedLabel = [[UILabel alloc] init];
    [recommendedView addSubview:recommendedLabel];
    [recommendedLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(recommendedView.mas_left).offset(0);
        make.right.equalTo(recommendedView.mas_right).offset(0);
        make.top.equalTo(recommendedView.mas_top).offset(0);
        make.bottom.equalTo(recommendedView.mas_bottom).offset(0);
    }];
    recommendedLabel.textColor = [UIColor colorWithRed:153 / 255.0 green:204 / 255.0 blue:51 / 255.0 alpha:1.0];
    recommendedLabel.text = @"他们的推荐";
    recommendedLabel.textAlignment = NSTextAlignmentCenter;
    
    UIView *stripView = [[UIView alloc] init];
    [recommendedView addSubview:stripView];
    [stripView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(recommendedLabel.mas_centerX).offset(0);
        make.height.mas_equalTo(2);
        make.bottom.equalTo(recommendedView.mas_bottom).offset(0);
        make.width.mas_equalTo(40);
    }];
    stripView.backgroundColor = [UIColor colorWithRed:153 / 255.0 green:204 / 255.0 blue:51 / 255.0 alpha:1.0];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isDetail){
        return self.articleArray.count;
    } else {
        if ([self.searchTextField.text isEqualToString:@""]) {
            return self.modelArray.count;
        } else {
            return self.strArray.count;
        }
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isDetail) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Main_Search_Detail_TableView_Cell" forIndexPath:indexPath];
        SearchArticleModel *model = [self.articleArray objectAtIndex:indexPath.row];
        cell.textLabel.text = model.title;
        return cell;
    } else {
        if ([self.searchTextField.text isEqualToString:@""]) {
            Main_Search_Recommended_TableView_Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"Main_Search_TableView_Cell" forIndexPath:indexPath];
            SearchRecommendedModel *model = [self.modelArray objectAtIndex:indexPath.row];
            cell.title = model.title;
            return cell;
        } else {
            Main_Search_Edit_TableView_Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"Main_Search_Edit_TableView_Cell" forIndexPath:indexPath];
            cell.str = [self.strArray objectAtIndex:indexPath.row];
            return cell;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isDetail) {
        SCB_Today_Default_detail_ViewController *Today_Default_detail_VC = [[SCB_Today_Default_detail_ViewController alloc] init];
        SearchArticleModel *model = [self.articleArray objectAtIndex:indexPath.row];
        Today_Default_detail_VC.contentId = model.contentId;
        NSLog(@"跳转");
        /**
         *  此处跳转使用模态 = =||
         */
        [self presentViewController:Today_Default_detail_VC animated:YES completion:^{
            
        }];
    } else {
        if ([self.searchTextField.text isEqualToString:@""]) {
            SCB_Today_Default_detail_ViewController *Today_Default_detail_VC = [[SCB_Today_Default_detail_ViewController alloc] init];
            SearchRecommendedModel *model = [self.modelArray objectAtIndex:indexPath.row];
            Today_Default_detail_VC.contentId = model.contentId;
            NSLog(@"跳转");
            /**
             *  此处跳转使用模态 = =||
             */
            [self presentViewController:Today_Default_detail_VC animated:YES completion:^{
        
            }];
        } else {
            self.searchTextField.text = [self.strArray objectAtIndex:indexPath.row];
            self.isDetail = YES;
            [self handleSearchDetailDate];
            [self.searchTextField resignFirstResponder];
        }
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    if ([self.searchTextField.text isEqualToString:@""]) {
        return YES;
    } else {
        self.isDetail = YES;
        [self handleSearchDetailDate];
    }
    return YES;
}

-(void)handleSearchDetailDate {

    NSString *urlStr = @"http://api.pianke.me/version4.0/search/listOfAll.php?sig=7F1970E64B094BEBF3078025A9538FEC";
    NSString *body = [NSString stringWithFormat:@"keyword=%@&pageNum=1&pageSize=10",self.searchTextField.text];
    NSDictionary *header = @{@"Authorization":HEADER};
    
    [self.articleArray removeAllObjects];
    [SCBNetTool POST:urlStr withBody:body withBodyStyle:SCBBodyString withHeaderFile:header withResponse:SCBJSON withSuccess:^(id result) {
        NSDictionary *dictionary = result;
        NSDictionary *dataDictionary = [dictionary valueForKey:@"data"];
        NSDictionary *articleDictionary = [dataDictionary valueForKey:@"article"];
        NSArray *articleArray = [articleDictionary valueForKey:@"list"];
        for (NSDictionary *dic in articleArray) {
            SearchArticleModel *model = [[SearchArticleModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.articleArray addObject:model];
        }
        [self.searchTableView reloadData];
        NSLog(@"%@",self.articleArray);
    } withFaolure:^(NSError *error) {
        NSLog(@"抓取失败%@",error);
    }];
    
}

-(void)textFieldDidChange:(id)sender {
    self.isDetail = NO;
    [self handleSearchDate];
}

-(void)handleSearchDate{
    NSString *urlStr = @"http://api.pianke.me/version4.0/search/suggest.php?sig=F60162184F85EB807ECEEE45546F9B58";
    NSString *body = [NSString stringWithFormat:@"keyword=%@",self.searchTextField.text];
    NSDictionary *header = @{@"Authorization":HEADER};
    [self.strArray removeAllObjects];
    [SCBNetTool POST:urlStr withBody:body withBodyStyle:SCBBodyString withHeaderFile:header withResponse:SCBJSON withSuccess:^(id result) {
        NSDictionary *dictionary = result;
        NSArray *array = [dictionary valueForKey:@"data"];
        for (NSString *str in array) {
            [self.strArray addObject:str];
        }
        [self.searchTableView reloadData];
    } withFaolure:^(NSError *error) {
        NSLog(@"抓取失败%@",error);
    }];
}

-(void)backButtonAction:(UIButton *)button{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)prefersStatusBarHidden{
    return YES;
}


@end
